package cn.huobi.org.controller;

import cn.huobi.basic.anno.PreAuthorize;
import cn.huobi.basic.util.AjaxResult;
import cn.huobi.basic.util.LoginContext;
import cn.huobi.basic.util.PageList;
import cn.huobi.org.domain.Department;
import cn.huobi.org.query.DepartmentQuery;
import cn.huobi.org.service.DepartmentService;
import cn.huobi.user.domain.Logininfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
@PreAuthorize
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    /**
     * 查询所有
     */
    @GetMapping
    @ApiOperation(value = "查询所有部门数据" )
    @PreAuthorize(name = "查询所有部门数据",sn = "department:findAll")
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    /**
     * 查询单条
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    @PreAuthorize(name = "通过ID单条查询",sn = "department:findById")
    public Department findById(@PathVariable("id") Long id){
        return departmentService.findById(id);
    }

    /**
     * 添加或修改
     */
    @PutMapping
    @PreAuthorize(name = "修改或添加部门",sn = "department:add")
    public AjaxResult add(@RequestBody Department department){
        if (department.getId() == null){
            // 添加
            departmentService.add(department);
        }else {
            // 修改
            departmentService.update(department);
        }
        return AjaxResult.me().success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "删除部门",sn = "department:detele")
    public AjaxResult detele(@PathVariable("id") Long id){
        departmentService.delete(id );
        return AjaxResult.me().success();
    }

    /**
     * 分页查询
     */
    @PostMapping
    @PreAuthorize(name = "部门分页查询",sn = "department:queryPage")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query, HttpServletRequest request){
        Logininfo loginContext = LoginContext.getLoginContext(request);
        System.out.println(loginContext);
        return departmentService.queryByPage(query);
    }

    /**
     *  批量删除
     */
    @PatchMapping
    @PreAuthorize(name = "批量删除部门",sn = "department:batchDel")
    public AjaxResult batchDel(@RequestBody List<Long> ids){
        departmentService.batchDel(ids);
        return AjaxResult.me().success();
    }

    /**
     * 部门联级查询
     */
    @PostMapping("/tree")
    @PreAuthorize(name = "部门联级查询",sn = "department:tree")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }
}
